// // import GamePlayFunction from "../Tools/GamePlayFunction";
// // import ShuaiAPI from "../Tools/ShuaiAPI";

import { _decorator, Component, Vec3, Node, Vec2, v2 } from 'cc';
const { ccclass, property } = _decorator;

import S2048_CardFunctions from "./S2048_CardFunctions";

@ccclass('S2048TouchManager')
export default class S2048_TouchManager extends Component {
    public static Instance: S2048_TouchManager;
    startPos: Vec3;
    currentPos: Vec3;
    endPos: Vec3;
    isPress: boolean = false;
    touchDistance = 20;
    onLoad() {
        S2048_TouchManager.Instance = this;
    }
    start() {
        this.registerEvent();
    }
    registerEvent() {
        this.node.on(Node.EventType.TOUCH_START, this.onEventStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onEventMove, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onEventCancel, this);
        this.node.on(Node.EventType.TOUCH_END, this.onEventEnd, this);
    }
    //    //触摸开始
    onEventStart(event) {
        //世界坐标
        this.startPos = event.getLocation();
        this.currentPos = event.getLocation();
        this.isPress = true;
        // console.log('start Event \n worldPoint=', this.startPos);
    }
    //    // 触摸移动
    onEventMove(event) {
        // console.log('onEventMove=', event);

        if (this.isPress == true) {
            this.currentPos = event.getLocation();
            let diff_x: number = this.currentPos.x - this.startPos.x;
            let diff_y: number = this.currentPos.y - this.startPos.y;

            let diff_max = Math.abs(diff_x) >= Math.abs(diff_y) ? diff_x : diff_y;
            if (Math.abs(diff_max) >= this.touchDistance) {
                this.isPress = false;

                let _direction: Vec2 = null;
                if (Math.abs(diff_x) >= Math.abs(diff_y)) {
                    if (diff_x > 0) {
                        _direction = v2(1, 0);
                    }
                    else {
                        _direction = v2(-1, 0);
                    }
                }
                else {
                    if (diff_y > 0) {
                        _direction = v2(0, 1);
                    }
                    else {
                        _direction = v2(0, -1);
                    }
                }

                S2048_CardFunctions.OperateSlide(_direction);
            }
        }
    }
    //    /**
    //     * 触摸
    //     * 当手指在目标节点区域外离开屏幕时
    //     * 比如说，触摸node的size是200x200。
    //     * 当超过这个区域时，就是触发这个事件
    //     * @param {*} event
    //     */
    onEventCancel(event) {
        this.endPos = event.getLocation();

        this.isPress = false;
    }
    //    //当手指在目标节点区域内离开屏幕时
    onEventEnd(event) {
        this.endPos = event.getLocation();

        this.isPress = false;
    }
}